<template>
    <div class="rowMate-add">
        <a-modal width="90%" :visible="visible" :title="modalOption.title" @ok="modalOption.onOk" :dialog-style="{ top: '20px' }"
            @cancel="modalOption.onCancel" :okText="modalOption.okText" :cancelText="modalOption.cancelText"
            class="yuan-modal rowMate-add-modal">
            <a-spin tip="Loading..." :spinning="formLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :label-col="{ style: { width: '100px' } }" :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">
                        <div class="form-panel-box yuan-form-col3">
                            <a-form-model-item class="yuan-form-item" label="原料类型" prop="rawType">
                                <a-radio checked>{{rawType}}</a-radio>
                            </a-form-model-item>

                            <!------------ 中药材 ------------->
                            <template v-if="rawType==='中药材'">
                                <a-form-model-item class="yuan-form-item" label="入库类型" prop="enterStorageType">
                                    <a-select class="yuan-form-input" v-model="formData.enterStorageType" placeholder="请选择"
                                        :disabled="!!editId">
                                        <a-select-option :value="item.key" v-for="item in enterList"
                                            :key="item.key">{{item.name}}</a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </template>

                            <!------------ 辅料 ------------->
                            <template v-else>
                                <a-form-model-item class="yuan-form-item" label="入库类型" prop="enterStorageType">
                                    <span class="yuan-form-input">采购入库</span>
                                </a-form-model-item>
                            </template>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item yuan-form-row-item yuan-form-col3" label="品名"
                                               prop="materialCode">
                                <!-- <a-select class="yuan-form-input" v-model="formData.materialCode" placeholder="请选择"
                                    @change="materialChange">
                                    <a-select-option :value="item.materialCode"
                                        v-for="item in materialList">{{item.varietyName}}</a-select-option>
                                </a-select> -->
                                <YuanSelectVue showSearch class="yuan-form-input" placeholder="请选择" :list="materialList"
                                               v-model="formData.materialCode" @change="materialChange" val="materialCode" name='varietyName'
                                               :defName="formData.varietyName" />

                                <a-button class="primary-empty-btn yuan-form-item-btn" @click="jump('/xls/#/materialMgt')">
                                    档案管理
                                </a-button>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="物料代码" prop="materialCode">
                                <span class="yuan-form-input" v-if="formData.materialCode">{{formData.materialCode }} </span>
                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>
                            </a-form-model-item>
                            <div class="clear-both"></div>

                            <!------------中药材 非溯源入库------------->
                            <template v-if="rawType==='中药材' && formData.enterStorageType==='NSY'">
                                <a-form-model-item class="yuan-form-item" label="来源" prop="source">
                                    <a-radio-group v-model="formData.source" :options="
                                    [
                                        { 'label': '自培育', value: '自培育' },
                                        { 'label': '野生', value: '野生' },
                                        { 'label': '动物类', value: '动物类' },
                                        { 'label': '矿物类', value: '矿物类' },
                                        { 'label': '特殊类', value: '特殊类' }
                                    ]"
                                    />
                                </a-form-model-item>
                                <div class="clear-both"></div>

                            </template>
                            <a-form-model-item class="yuan-form-item yuan-form-row-item" label="入库批号" prop="enterStorageBatch">
                                <a-input class="yuan-form-input" v-model="formData.enterStorageBatch" placeholder="请输入"></a-input>
                                <a-button class="primary-empty-btn yuan-form-item-btn" @click="getStorageBatch">
                                    系统生成
                                </a-button>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="入库时间" prop="enterStorageTime">
                                <a-date-picker class="yuan-form-input" valueFormat="YYYY-MM-DD"
                                    v-model="formData.enterStorageTime" placeholder="选择日期" />
                            </a-form-model-item>



                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item" label="入库数量" prop="enterStorageNum">
                                <a-input class="yuan-form-input" type="number" v-model="formData.enterStorageNum"
                                    placeholder="请输入" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="数量单位" prop="unit">

                                <YuanSelectVue class="yuan-form-input" placeholder="请选择" :list="unitList" v-model="formData.unit"
                                    val="unit" name='unit' :defName="formData.unit" />
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="产地" prop="placeOfOrigin">

                                <YuanSelectVue class="yuan-form-input" placeholder="请选择" :list="placeOfOrigin"
                                    v-model="formData.placeOfOrigin" :defName="formData.placeOfOrigin"
                                    v-if="placeOfOrigin && placeOfOrigin.length>0" />

                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="生产日期" prop="productionTime">
                                <a-date-picker class="yuan-form-input" valueFormat="YYYY-MM-DD" v-model="formData.productionTime"
                                    placeholder="选择日期" />
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item yuan-form-row-item" label="操作人" prop="operatorId">
                                <!-- <a-select class="yuan-form-input" v-model="formData.operatorId" placeholder="请选择">
                                    <a-select-option :value="item.userId"
                                        v-for="item in accountList">{{item.name}}</a-select-option>
                                </a-select> -->

                                <YuanSelectVue class="yuan-form-input" placeholder="请选择" :list="accountList"
                                    v-model="formData.operatorId" val="userId" name='name' :defName="formData.operator"
                                    @change="accountChange" />

                                <a-button class="primary-empty-btn yuan-form-item-btn" @click="jump('/xls/#/memberManagement')">
                                    员工管理
                                </a-button>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="仓储条件" prop="storageCondition">
                                <a-radio-group v-model="formData.storageCondition"
                                    :options="[{ 'label': '常温', value: '常温' },  { 'label': '阴凉', value: '阴凉' }]" />
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="选择仓库" prop="warehouseId">
                                <!-- <a-select class="yuan-form-input" v-model="formData.warehouseId" placeholder="请选择"
                                    @change="warehouseChange">
                                    <a-select-option :value="item.id"
                                        v-for="item in warehouseList">{{item.name}}</a-select-option>
                                </a-select> -->

                                <YuanSelectVue class="yuan-form-input" placeholder="请选择" :list="warehouseList"
                                    v-model="formData.warehouseId" @change="warehouseChange" val="id" name='name'
                                    :defName="formData.warehouse" />
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item yuan-form-row-item" label="供应商" prop="supplierId">
                                <!-- <a-select class="yuan-form-input" v-model="formData.supplierId" placeholder="请选择">
                                    <a-select-option :value="item.id" v-for="item in supplierList">{{item.name}}</a-select-option>
                                </a-select> -->

                                <YuanSelectVue class="yuan-form-input" placeholder="请选择" :list="supplierList"
                                    v-model="formData.supplierId" val="id" name='name' :defName="'已删除'"  showSearch/>

                                <a-button class="primary-empty-btn yuan-form-item-btn" @click="jump('/xls/#/supplierMgt')">
                                    供应商管理
                                </a-button>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="有效期至" prop="indate">
                                <a-date-picker class="yuan-form-input" valueFormat="YYYY-MM-DD" v-model="formData.indate"
                                    placeholder="选择日期" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="质量标准" prop="massStandard">
                                <a-input class="yuan-form-input" v-model="formData.massStandard" placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="厂家批号" prop="venderProductionBatch">
                                <a-input class="yuan-form-input" v-model="formData.venderProductionBatch"
                                    placeholder="请输入"></a-input>
                            </a-form-model-item>

                            <div class="clear-both"></div>

                        </div>
                    </div>

                </a-form-model>
            </a-spin>
        </a-modal>
        <a-modal :visible="confirmVisible" title="提示" okText="确定" cancelText="取消" @cancel="confirmVisible=false" @ok="confirmSave">
               <a-result title="确定要提交吗?"></a-result>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import nextApi, {
    AccountListRes,
    MaterialListRes,
    ProductionUsePackRes,
    ProListRes,
    SupplierListRes,
    WarehouseListRes,
} from "@/api/nextApi";
import { format } from "@/utils";
@Component({
    name: "rowMateAdd",
    components: {},
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: "" }) rawType!: string;
    @Prop({ default: "" }) editId!: string;
    @Watch("visible")
    visibleChange() {
        if (this.visible) this.getDetail();
    }
    formLoading = false;
    modalOption = {
        title: "新增入库",
        okText: "保存",
        cancelText: "取消",
        onOk: () => {
            // this.modalOk();
            this.showConfirmModal();
        },
        onCancel: () => {
            this.closeModal();
        },
    };
    enterList = [
        { key: "SY", name: "溯源入库" },
        { key: "NSY", name: "非溯源入库" },
    ];
    rules = {
        rawType: [{ required: true, message: "请选择物料", trigger: "blur" }],
        enterStorageType: [{ required: true, message: "请选择入库类型", trigger: "blur" }],
        source: [{ required: true, message: "请选择来源", trigger: "blur" }],
        enterStorageBatch: [{ required: true, message: "请输入入库批号", trigger: "blur" }],
        enterStorageTime: [{ required: true, message: "请选择入库时间", trigger: "change" }],
        materialCode: [{ required: true, message: "请选择品名", trigger: "blur" }],
        enterStorageNum: [{ required: true, message: "请输入入库数量", trigger: "blur" }],
        unit: [{ required: true, message: "请选择数量单位", trigger: "blur" }],
        placeOfOrigin: [{ required: false, message: "请选择产地", trigger: "blur" }],
        operatorId: [{ required: true, message: "请选择操作人", trigger: "blur" }],
        storageCondition: [{ required: true, message: "请选择仓储条件", trigger: "blur" }],
        warehouseId: [{ required: true, message: "请选择仓库", trigger: "blur" }],
        supplierId: [{ required: true, message: "请选择供应商", trigger: "blur" }],
    };
    formData: any = {};
    resetForm() {
        this.formData = {};
    }
    async mounted() {
        this.resetForm();
    }
    confirmVisible = false;
    showConfirmModal(){
        this.confirmVisible = true;
    }
    confirmSave() {
        this.confirmVisible = false;
        this.modalOk();
    }
    closeModal() {
        this.resetForm();

        this.$emit("closeModal");
        setTimeout(() => {
            (this.$refs.form as any).resetFields();
        }, 200);
    }
    modalOk() {
        (this.$refs.form as any).validate(async (valid: any) => {
            if (valid) {
                this.formLoading = true;
                this.formData.id = this.editId;
                try {
                    const res = await nextApi.addRawInfo(this.formData);
                    this.$message.success(res.msg);
                    this.closeModal();
                    this.$emit("resetList");
                } finally {
                    this.formLoading = false;
                }
            }
        });
    }
    async getDetail() {
        // (this.$refs.form as any).resetFields();
        this.formLoading = true;
        Promise.all([
            this.getMaterials(),
            this.getUnitList(),
            this.getAccountList(),
            this.getWarehouseList(),
            this.getSupplierList(),
        ]).then(async () => {
            let data: any = {};
            if (this.editId) {
                const res = await nextApi.getRawInboundDetail({ id: this.editId });
                this.formData = { ...res.data };
                this.materialChange();
            } else {
                data = {
                    rawType: this.rawType + "",
                    source: "自培育",
                    enterStorageType: "NSY",
                    storageCondition: "常温",
                    enterStorageBatch:''
                };

                //辅料
                if (this.rawType === "辅料") {
                    data.enterStorageType = "CG"; //默认为采购入库
                }
                this.formData = data;
                this.formData.operatorId = this.accountList[0].userId
                this.formData.operator = this.accountList[0].name
                this.formData.unit = "kg";
            }

            this.formLoading = false;
        });
    }
    materialList: MaterialListRes[] = [];
    async getMaterials() {
        const res = await nextApi.getMaterialList({
            productType: this.rawType,
            state: 0,
        });
        this.materialList = res.data?.rows || [];
    }
    placeOfOrigin: string[] = [];
    materialChange() {
        const find = this.materialList.find((item) => item.materialCode === this.formData.materialCode);
        if (find) {
            this.formData.varietyName = find.varietyName;
            this.formData.basinymLatin = find.basinymLatin;
            this.formData.materialCode = find.materialCode;
            this.formData.basinymName = find.basinymName;
            this.placeOfOrigin = find.placeOfOrigin;
            this.formData.source = find.source;
        }
    }

    unitList: { unit: string }[] = [];
    async getUnitList() {
        if (this.unitList && this.unitList.length > 0) return;
        const res = await nextApi.getUnitList();
        this.unitList = res.data || [];
    }

    accountList: AccountListRes[] = [];
    async getAccountList() {
        if (this.accountList && this.accountList.length > 0) return;
        const res = await nextApi.getAccountList({});
        this.accountList = res.data?.rows || [];
        let curAccount;
        const siteUserInfo = localStorage.getItem('siteUserInfo') ?? '';
        if(siteUserInfo){
            try{
                curAccount = JSON.parse(siteUserInfo)
                let curUserInfo: AccountListRes = {
                    name:curAccount.name,
                    userId:curAccount.id,
                    phone:curAccount.phone,
                    organizationName:curAccount.organizationName
                }
                this.accountList.unshift(curUserInfo)
            }catch (error) {
                console.error('Failed to parse siteUserInfo:', error);
                curAccount = null
            }
        }else{
            curAccount = null
        }
    }
    accountChange() {
        const find = this.accountList.find((item) => item.userId === this.formData.operatorId);
        if (find) {
            this.formData.operator = find.name;
        }
    }

    warehouseList: WarehouseListRes[] = [];
    async getWarehouseList() {
        if (this.warehouseList && this.warehouseList.length > 0) return;
        const res = await nextApi.getWarehouseList({
            state: 1,
        });
        this.warehouseList = res.data || [];
    }
    warehouseChange() {
        const find = this.warehouseList.find((item) => item.id === this.formData.warehouseId);
        if (find) {
            this.formData.warehouse = find.name;
        }
    }

    supplierList: SupplierListRes[] = [];
    async getSupplierList() {
        if (this.supplierList && this.supplierList.length > 0) return;
        const res = await nextApi.getSupplierList({ state: 1 });
        this.supplierList = res.data?.rows || [];
    }

    jump(url: string) {
        window.open(url);
    }
    getStorageBatch() {
        const time = new Date().getTime();

        let randomNumber: number | string = Math.floor(Math.random() * 100);

        // 如果随机数小于10，则在前面添加一个0
        if (randomNumber < 10) {
            randomNumber = "0" + randomNumber;
        }
        this.formData.enterStorageBatch = format(time, "yyMMddhhmm" + randomNumber);
        // const timestamp = Date.now();
        // const randomNumber = Math.floor(1000 + Math.random() * 9000);
        // this.formData.enterStorageBatch = `Y${timestamp}${randomNumber}`;
    }
}
</script>
<style lang="scss"></style>
